package org

import (
    "fmt"
	"strings"
	"encoding/json"
	"dhfshop/utils/response"
	"dhfshop/models/org"
	"dhfshop/models/member"
	"dhfshop/controllers/base"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
	"wxsdk/miniapp/utils/security"
)

type PhoneObjController struct {
	base.BaseController
}

/*******************************************************************
用户同意的话，提示e.detail.errMsg='getPhoneNumber:ok'
用户不同意的话，提示e.detail.errMsg='getPhoneNumber:fail user deny'
encryptedData和iv都是undefined
*******************************************************************/
func (this *PhoneObjController) GetPhoneInfo() {
	v := struct {
		EncryptedData  string   `form:"encryptedData" valid:"Required"`
		Iv             string   `form:"iv" valid:"Required"`
		OpenId         string   `form:"open_id" valid:"Required"`
	}{} 
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return 
	}
	sessionKey := ""
	curSysRoleId := this.Ctx.Input.GetData("curRoleId").(int)
	if curSysRoleId == 1 {
	    if member, err := member.GetMemberByOpenId(v.OpenId); err == nil {
		    sessionKey = member.SessionKey
		}
	} else if curSysRoleId == 2 {
	    if user, err := org.GetUserIdByOpenId(v.OpenId); err == nil {
		    sessionKey = user.SessionKey
		}
	} else {
	
	}
	if len(sessionKey) < 5 {
		this.ServeError(fmt.Sprintf("session key is invalid, openid:", v.OpenId))
	    return
	}
	/*
	beego.Debug("v.OpenId:", v.OpenId)
	beego.Debug("sessionKey:", sessionKey)
	beego.Debug("v.EncryptedData:", v.EncryptedData)
	beego.Debug("v.Iv:", v.Iv)
	*/
	decrypted, err := security.WXBizDataDecrypt(sessionKey, v.EncryptedData, v.Iv)
	if err != nil {
		if strings.Contains(err.Error(), "illegal base64") {
			//this.Ctx.Output.SetStatus(401)
			this.ServeCodeError("-41003", response.LangConf.Get("-41003").MustString())
		}else{
		    this.ServeError(err.Error())
		}
		beego.Debug(err.Error())
		return
	}
	phoneObj := struct {
		PhoneNumber     string  `json:"phoneNumber"`
		PurePhoneNumber string  `json:"purePhoneNumber"`
		CountryCode     string  `json:"countryCode"` 
	}{}
	if len(string(decrypted)) < 8 {
	   this.ServeError(string(decrypted))
	   return
	}
	err = json.Unmarshal(decrypted, &phoneObj)
	if err != nil {
	    if strings.Contains(err.Error(), "invalid character") {
			//this.Ctx.Output.SetStatus(401)
			this.ServeCodeError("-41003", response.LangConf.Get("-41003").MustString())
		}else{
		    this.ServeError(err.Error())
		}
		beego.Debug(err.Error())
		
		return
	}
	if curSysRoleId == 1 {
	    members := &member.MemberValue{OpenID:v.OpenId, Phone:phoneObj.PhoneNumber}
		if err = member.UpdateMemberByOpenId(members, "phone"); err != nil {
		    beego.Debug(err.Error())
		}
	} else if curSysRoleId == 2 {
	    user := &org.User{OpenID:v.OpenId, Mobile:phoneObj.PhoneNumber}
		if err = org.UpdateUsersByOpenId(user, "mobile"); err != nil {
		    beego.Debug(err.Error())
		}
	} else {
	
	}
	this.Data["json"] = map[string]string{
	    "open_id": v.OpenId,
		"phone_number": phoneObj.PhoneNumber,
		"pure_phone_number": phoneObj.PurePhoneNumber,
		"country_code": phoneObj.CountryCode,
	}
	this.ServeJSON()
}
